<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/20 0020
 * Time: 14:03
 */

namespace backend\controllers;


use backend\assets\EChartsAsset;
use backend\components\BaseComponentController;
use common\components\ActionsComponents\ListViewAction;
use common\components\GlobalUrlComponent;
use common\models\WxFollowLog\WxFollowLog;
use common\models\WxPublic\WxPublic;
use yii\helpers\Url;

class WxPublicController extends BaseComponentController
{
    public function actions()
    {
        return [
            "index" => [
                "class" => ListViewAction::class,
                "model" => WxPublic::class,
                "with" => ["area", "eNumber" => function($query){
                    $query->andWhere([
                        "created_date" => date("Y-m-d", strtotime("-1 day"))
                    ]);
                }, "fNumber" => function($query){
                    $query->andWhere([
                        "created_date" => date("Y-m-d", strtotime("-1 day"))
                    ]);
                }],
            ]
        ]; // TODO: Change the autogenerated stub
    }

    public function actionItem()
    {
        if ( ($id = $this->get("id")) ) {
            $wxPublic = WxPublic::findOne($id);
            if ( !$wxPublic ) {
                return $this->redirect(Url::to(["index"]));
            }
            $area = "";
            if ( $wxPublic->area ) {
                foreach ( $wxPublic->area as $item ) {
                    $area .= $item["city"] . ",";
                }
                $area = rtrim($area, ",");
            }
        } else {
            $area = "";
            $wxPublic = [];
        }
        $this->setGuide([
            "公众号回调地址请填写为：" . GlobalUrlComponent::buildApiUrl("/wechat/services"),
            "获取二维码地址为：" . GlobalUrlComponent::buildApiUrl("/wx-public/qr"),
        ], "red");
        return $this->render("item", [
            "ret" => $wxPublic,
            "area" => $area
        ]);
    }

    public function actionChart()
    {
        $wxFollowLog = WxFollowLog::find()->where([
            "wx_public_id" => $this->get("id"),
            "created_ym" => date("Y-m"),
        ])->select(["count(*) num", "created_date"])->groupBy("created_date");
        $wxFollowLog = $wxFollowLog->asArray()->all();
        $this->layout = self::LAYER_CONTENT;
        return $this->render("chart", [
            "ret" => EChartsAsset::formatData($wxFollowLog, "created_date", "num")
        ]);
    }

    public function actionSet()
    {
        if ( WxPublic::setRow($this->post(), $this->post("id")) ) {
            return $this->jsonResponse(self::RESPONSE_SUCCESS);
        }
        return $this->jsonResponse(self::RESPONSE_FAILURE, WxPublic::error());
    }
}